package com.lianda.java8.functional.base;

import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;

/**
 * java8自带函数式编程接口
 * https://my.oschina.net/thinwonton/blog/2992371
 */
public class BasicFunctionalMain {
    public static void main(String[] args) throws Exception {

        //Supplier无入参，有返回值
        Supplier<Integer> supplier = () -> 10;
        System.out.println("supplier#get====>" + supplier.get());

        //Consumer有1个入参，无返回值
        Consumer<Integer> print1 = x -> System.out.println(x);
        print1.accept(10);
        System.out.println("==================");

        Consumer<Integer> print2 = x -> System.out.println(x);
        Consumer<Integer> print2Plus = x -> System.out.println(x + x);
        print2.andThen(print2Plus).accept(10);

        System.out.println("==================");


        // Function<T, R>
        // 接收T类型参数，返回R类型参数；
        Function<Integer, Integer> plusSelf = x -> x + x;
        System.out.println(plusSelf.apply(10));
        System.out.println("==================");

        //compose：accept获取到的参数，先执行compose里面的Function，再执行原Function
        Function<Integer, Integer> plusSelf1 = x -> {
            System.out.println("plusSelf1");
            return x + x;
        };

        Function<Integer, String> toString = x -> {
            System.out.println("toString");
            return x.toString();
        };

        //整数10先自加变成20，然后由toString转换成字符串
        String string1 = toString.compose(plusSelf1).apply(10);
        System.out.println(string1);
        System.out.println("==================");


        //andThen，与compose相反。先执行原Function，在执行andThen里面的Function
        Function<Integer, Integer> plusSelf2 = x -> {
            System.out.println("plusSelf2");
            return x + x;
        };
        Function<Integer, String> toString2 = x -> {
            System.out.println("toString2");
            return String.valueOf(x);
        };

        //输出20, 先自加，再转换成字符串
        String string2 = plusSelf2.andThen(toString2).apply(10);
        System.out.println("==================");

        // Predicate<T>
        // 输入T类型的参数，完成true/false判断，返回boolean类型
        Predicate<String> test = x -> "test".equals(x);
        //执行test方法，完成判断
        System.out.println(test.test("test"));
    }
}
